<?php

namespace app\screen\controller\railway;

use app\BaseController;
use app\common\model\broadcast\DeviceRod;
use app\common\model\haikang\HkConsumerMsg;
use app\common\model\haikang\HkConsumerMsgFd;
use app\common\model\haikang\HkConsumerMsgWeek;
use app\common\model\haikang\VideoPlayback;
use app\common\model\work_area\HkDeviceSerial;
use app\common\model\work_area\WorkAreaStandVoice;
use app\common\service\broadcast\IpBroadcastService;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("报警回调相关")
 */
class AlarmCallback extends BaseController
{

    /**
     * @Apidoc\Title("图片回调")
     * @Apidoc\Url("/screen/railway.AlarmCallback/imageCallback")
     * @Apidoc\Param("type",type="int",require=true, desc="1图片回调 2视频回调")
     * @Apidoc\Param("yj_data_id",type="string",require=true, desc="回调数据唯一标识")
     * @Apidoc\Param("channel_no",type="string",require=true, desc="type=1 传通道名称")
     * @Apidoc\Param("device_serial",type="string",require=true, desc="type=1 传设备号")
     * @Apidoc\Param("file_url",type="string",require=true, desc="抓拍图片网络地址、视频地址")
     * @Apidoc\Param("msg_type",type="string",require=true, desc="抓拍类型 移动侦测、雷达侦测、周界入侵")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="object", desc="返回说明")
     */
    public function imageCallback()
    {
        try {
            $param = $this->request->param();
            $hk_consumer_msg_fd = HkConsumerMsgFd::whereOr(['type' => 1])->whereOr(['work_area_stand_id' => 1])->column('fd');
            
            if ($param['type'] == 1) {
                Validate([
                    'yj_data_id|回调数据唯一标识' => 'require',
                    'channel_no|通道名称' => 'require',
                    'device_serial|设备号' => 'require',
                    'file_url|抓拍图片网络地址' => 'require',
                ])->check($param);
                $hk_device_serial = HkDeviceSerial::alias('a')
                    ->join("work_area_stand b ", " b.id = a.work_area_stand_id", 'left')
                    ->join("work_area c ", " c.id = b.work_area_id", 'left')
                    ->where(['device_serial' => $param['device_serial'], 'channel_no' => $param['channel_no']])
                    ->field(['a.id', 'a.device_rod_id', 'a.work_area_stand_id', 'a.name', 'b.name bname', 'c.name st_line'])
                    ->find();
                $time = time();
                $msg_type = input('msg_type/s', 'Other');
                switch ($msg_type) {
                    case "Other":
                        $msg_type = 'AI检测';
                        break;
                    case "移动侦测":
                        $msg_type = '移动侦测';
                        break;
                    case "雷达侦测":
                        $msg_type = '雷达侦测';
                        break;
                }
                if (!empty($hk_device_serial)) {
                     
                    $data = [
                        'device_rod_id' => $hk_device_serial->device_rod_id,
                        'device_rod_name' => DeviceRod::where(['id' => $hk_device_serial->device_rod_id])->value('name'),
                        'work_area_stand_id' => $hk_device_serial->work_area_stand_id,
                        'platform_type' => 3,
                        'msg_id' => $param['yj_data_id'],
                        'yj_data_id' => $param['yj_data_id'],
                        'msg_type' => 'ai_message_task_result',
                        'msg_name' => $msg_type,
                        'channel_no' => $param['channel_no'],
                        'device_serial' => $param['device_serial'],
                        'device_name' => $hk_device_serial->name,
                        'device_serial_id' => $hk_device_serial->id,
                        'date_time' => $time,
                        'timestamp' => $time,
                        'image_url' => $param['file_url'],
                        'server_img_url' => $param['file_url'],
                        'st_line' => $hk_device_serial->st_line,
                        'cname' => $hk_device_serial->bname
                    ];
                    //写入文件记录
                    HkConsumerMsg::create($data);
                    HkConsumerMsgWeek::create($data);
                    //播放广播
                    $voice_file = WorkAreaStandVoice::where(['hk_device_serial_id' => $hk_device_serial->id, 'event_type' => $msg_type])
                        ->order("id DESC")
                        ->cache(60)
                        ->value('file');
                    //检查20秒以内是否存在报警
                    $play_url_time = cache('play_url_time' . $hk_device_serial->id);
            
                    //每天8点到晚上20点播放
                    $startTimeStamp = strtotime(date('Y-m-d 8:00:00'));
                    $endTimeStamp = strtotime(date('Y-m-d 20:00:00'));
                    if (
                        !empty($voice_file)
                        && empty($play_url_time)
                        && $time >= $startTimeStamp
                        && $time <= $endTimeStamp
                    ) {
                       
                        //语音文件服务器域名
                        $play_url = 'http://ai.admin.lgsid.com/' . $voice_file;
                        //远程调用ip广播
                        IpBroadcastService::speech([
                            'url' => $play_url,
                            'hk_device_serial_id' => $hk_device_serial->id
                        ]);
                        $data['play_url'] = $play_url;
                        cache('play_url_time' . $hk_device_serial->id, 1, 23);
                        
                        //图片推送到大屏
                        if (!empty($hk_consumer_msg_fd)) {
                            $url = "https://aisocket.zyckj.club/consumerMsgPush";
                            json_post($url, ['fd' => $hk_consumer_msg_fd, 'data' => $data]);
                        }
                    }
                }
            } else {
                Validate([
                    'yj_data_id|回调数据唯一标识' => 'require',
                    'file_url|抓拍图片网络地址' => 'require',
                ])->check($param);
                VideoPlayback::create([
                    'yj_data_id' => $param['yj_data_id'],
                    'file_url' => $param['file_url'],
                    'hk_consumer_msg_id' => HkConsumerMsg::where(['yj_data_id' => $param['yj_data_id']])->value('id')
                ]);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return ajaxJson(0, $e->getMessage());
        }
        
        return ajaxJson(1, '成功');
    }
}